package ch2.sq;

import java.util.*;

class Stud implements Comparable<Stud> {
    private String name;    //姓名
    private Integer age;    //年龄

    public Stud(String name, int age) {    //构造方法
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "[" + name + "," + age + "]";
    }
    public String getname() {
        return name;
    }

    @Override
    public int compareTo(Stud stud) {  // 用于按age递增排序
        return this.age.compareTo(stud.age);
    }
}

public class Exam2_9 {
    public static void main(String[] args) {
        List<Stud> studList = new ArrayList<>();
        studList.add(new Stud("John", 18));
        studList.add(new Stud("Mary", 17));
        studList.add(new Stud("Smith", 20));
        studList.add(new Stud("Tom", 18));
        System.out.println("初始序列:\n  " + studList);

        // 排序方法1
        Collections.sort(studList);
        System.out.println("按年龄递增排序:\n  " + studList);

        // 排序方法2
        studList.sort(new Comparator<Stud>() {
            @Override
            public int compare(Stud o1, Stud o2) {
                return o1.getname().compareTo(o2.getname());
            }
        });
        studList.sort((o1, o2) -> {                //用于按姓名递增排序
            return o1.getname().compareTo(o2.getname());
        });
        System.out.println("按姓名递增排序:\n  " + studList);

        //排序方法3
        studList.sort(Comparator.comparing(Stud::getname).reversed());
        System.out.println("按姓名递减排序:\n  " + studList);


    }
} 
